package com.alander.nexusgo.im.service;

import cn.hutool.json.JSONUtil;
import com.alander.nexusgo.im.model.dto.ImMsgBody;
import com.alander.nexusgo.im.netty.ImConnectionManager;
import com.alander.nexusgo.im.constants.ImConstants;
import com.alander.nexusgo.im.constants.ImMsgCodeEnum;
import com.alander.nexusgo.im.model.dto.ImMsg;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 消息服务类
 */
@Service
public class MessageService {
    
    @Autowired
    private MessageStorageService messageStorageService;

    /**
     * 发送消息给指定用户
     *
     * @param imMsgBody 消息体
     * @return 是否发送成功
     */
    public boolean sendMsg(ImMsgBody imMsgBody) {
        // 创建IM消息
        ImMsg imMsg = new ImMsg();
        imMsg.setMagic(ImConstants.DEFAULT_MAGIC);
        imMsg.setCode(ImMsgCodeEnum.IM_BIZ_MSG.getCode());
        
        // 序列化消息体
        String bodyJson = JSONUtil.toJsonStr(imMsgBody);
        byte[] bodyBytes = bodyJson.getBytes();
        imMsg.setLen(bodyBytes.length);
        imMsg.setBody(bodyBytes);
        
        // 发送单聊消息
        if (imMsgBody.getAppId() == 10002) { // 单聊应用
            // 存储消息
            boolean saved = messageStorageService.saveSingleMessage(
                imMsgBody.getUserId(), 
                (long) imMsgBody.getBizCode(), 
                imMsgBody.getData()
            );
            
            Channel targetChannel = ImConnectionManager.getUserChannel(imMsgBody.getBizCode());
            if (targetChannel != null && targetChannel.isActive()) {
                targetChannel.writeAndFlush(imMsg);
                return saved;
            }
            return saved;
        } 
        // 发送群聊消息
        else if (imMsgBody.getAppId() == 10001) { // 群聊应用
            // 存储消息
            boolean saved = messageStorageService.saveGroupMessage(
                imMsgBody.getBizCode(), 
                imMsgBody.getUserId(), 
                imMsgBody.getData()
            );
            
            ChannelGroup roomGroup = ImConnectionManager.getChatRoomGroup(imMsgBody.getBizCode());
            if (roomGroup != null) {
                roomGroup.writeAndFlush(imMsg);
                return saved;
            }
            return saved;
        }
        
        return false;
    }

    /**
     * 批量发送消息
     *
     * @param imMsgBodyList 消息体列表
     */
    public void batchSendMsg(List<ImMsgBody> imMsgBodyList) {
        for (ImMsgBody imMsgBody : imMsgBodyList) {
            sendMsg(imMsgBody);
        }
    }
    
    /**
     * 获取两个用户之间的消息记录
     * @param userId1 用户1 ID
     * @param userId2 用户2 ID
     * @return 消息列表
     */
    public java.util.List<com.alander.nexusgo.im.model.entity.SingleMessage> getMessagesBetweenUsers(Long userId1, Long userId2) {
        return messageStorageService.getMessagesBetweenUsers(userId1, userId2);
    }
    
    /**
     * 获取群组最近的消息
     * @param groupId 群组ID
     * @param limit 限制数量
     * @return 消息列表
     */
    public java.util.List<com.alander.nexusgo.im.model.entity.GroupMessage> getRecentGroupMessages(Integer groupId, int limit) {
        return messageStorageService.getRecentGroupMessages(groupId, limit);
    }
    
    /**
     * 获取用户未读消息
     * @param receiverId 接收者ID
     * @return 未读消息列表
     */
    public java.util.List<com.alander.nexusgo.im.model.entity.SingleMessage> getUnreadMessages(Long receiverId) {
        return messageStorageService.getUnreadMessages(receiverId);
    }
    
    /**
     * 标记消息为已读
     * @param receiverId 接收者ID
     * @param senderId 发送者ID
     * @return 更新记录数
     */
    public int markMessagesAsRead(Long receiverId, Long senderId) {
        return messageStorageService.markMessagesAsRead(receiverId, senderId);
    }
}